package com.cleaner.base.ktx

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.text.format.Formatter
import androidx.core.content.ContextCompat
import com.cleaner.base.appContext
import kotlin.math.ceil


/**
 * 获取已使用的运行内存
 * 单位GB
 */
fun getAvailMemory() = getMemory("availMem")

/**
 * 获取总运行内存
 * 单位GB
 */
fun getTotalMemory() = ceil(getMemory("totalMem").toDouble()).toFloat()

/**
 * 获取运行内存使用情况
 */
fun getMemoryUsage(): Float = (getAvailMemory() / getTotalMemory()) * 100

private fun getMemory(type: String): Float {
    val am = appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val mi = ActivityManager.MemoryInfo()
    am.getMemoryInfo(mi)
    return try {
        if (type == "availMem") {
            Formatter.formatFileSize(appContext, mi.availMem)
        } else {
            Formatter.formatFileSize(appContext, mi.totalMem)
        }.run {
            replace("GB", "").trim().toFloat()
        }
    } catch (e: Throwable) {
        0f
    }
}

fun hasPermission(permission: String) = ContextCompat.checkSelfPermission(
    appContext, permission
) == PackageManager.PERMISSION_GRANTED


//获取仅出现在桌面上的app
fun getLauncherApps(): List<ResolveInfo> {
    val intent = Intent()
    intent.addCategory(Intent.CATEGORY_LAUNCHER)
    intent.action = Intent.ACTION_MAIN
    return appContext.packageManager.queryIntentActivities(intent, 0)
}

fun startGooglePlay() {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse("market://details?id=" + appContext.packageName)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    //存在手机里没安装应用市场的情况，跳转会包异常，做一个接收判断
    //存在手机里没安装应用市场的情况，跳转会包异常，做一个接收判断
    if (intent.resolveActivity(appContext.packageManager) != null) {
        appContext.startActivity(intent)
    } else {
        intent.data =
            Uri.parse("https://play.google.com/store/apps/details?id=" + appContext.packageName)
        if (intent.resolveActivity(appContext.packageManager) != null) {
            appContext.startActivity(intent)
        }
    }
}